import { Button, Radio, Image, Space, message, Input, InputNumber } from 'antd';
import Logo from '../components/Logo';
import styles from './index.less';
import { history } from '@umijs/max';
import { useRequest } from 'ahooks';
import { getAddressList } from '@/services/address';
import { useEffect, useRef, useState } from 'react';
import { DoubleRightOutlined, MinusOutlined, PlusOutlined } from '@ant-design/icons';
import classnames from 'classnames';
import { money } from '@/utils/money';
import { createOrder, getPayType, getTradeType, previewOrder } from '@/services/order';
import AddressModal from './AddressModal';
import { cloneDeep } from 'lodash';

const style: React.CSSProperties = {
    display: 'flex',
    flexDirection: 'column',
    gap: 15,
};

const orderSettlement = () => {
    const skuList = history?.location?.state?.skuList || []

    const [quantityList, setQuantityList] = useState(skuList?.map((item) => { return item.quantity} ))
   
    const [checkAddress, setCheckAddress] = useState<any>({});
    const [moreAdd, setMoreAdd] = useState<any>(false);
    const [transactionModes, setTransactionModes] = useState<any>(1);
    const [paymentType, setPaymentType] = useState<any>("WECHAT");

    const [isModalOpen, setIsModalOpen] = useState(false)

    const {data: addressList, run: getAddList} = useRequest(() => {
        return getAddressList().then(res => {
            res?.data?.forEach((item) => {
                if (item.isDefault) {
                    setCheckAddress(item)
                }
            })
            return res.data
        })
    })

    // 浏览订单金额
    const {data: viewData} = useRequest(() => {
        if (!checkAddress?.id) return Promise.reject()
        const data = {
            goodsList: skuList?.map((item, index) => {
                return {
                goodsId: item.goodsId,
                skuId: item.skuId,
                quantity: quantityList[index] || 0
            }}),
            shippingAddressId: checkAddress?.id,
            transactionModes,
            paymentType
        }
        return previewOrder(data).then(res => {
            if (res.code === 200) {
                return res.data
            } else {
                message.warning(res.message)
            }
        })
    },
    {
        refreshDeps: [transactionModes, checkAddress?.id, quantityList]
    }
)
    const {data: payTyptList} = useRequest(() => {
        if (!viewData?.payablePrice) return Promise.reject()
        return getPayType({ payAmount: viewData?.payablePrice }).then(res => {
            return res.data
        })
    }, {
        refreshDeps: [viewData?.payablePrice]
    })

    const {data: tradeList} = useRequest(() => {
        return getTradeType().then(res => {
            return res.data
        })
    })

    const createOrderSub = () => {
        const data = {
            goodsList: skuList?.map((item) => {
                return {
                goodsId: item.goodsId,
                skuId: item.id,
                quantity: item.quantity
            }}),
            shippingAddressId: checkAddress?.id,
            transactionModes,
            paymentType
        }
        createOrder(data).then(res => {
            if (res.code === 200) {
                history.push(`/pay?orderNo=${res.data}&paymentType=${paymentType}&payablePrice=${viewData?.payablePrice}`)
            } else {
                message.warning(res.message)
            }
        })
    }
    
    return (
        <div className={styles.page}>
            <div style={{ width: '1400px' }}>
                <div className={styles.top}>
                    <Logo />
                    <div className={styles.title}>
                        订单结算页面
                    </div>
                </div>
                <div className={classnames(styles.address, !moreAdd ? styles.noMore : '')}>
                    <div style={{ display: 'flex', justifyContent: 'space-between' }}>
                        <div style={{ fontWeight: 600 }}>收货人信息</div>
                        <Button color="primary" onClick={() => setIsModalOpen(true)} variant="link" >新增收获地址</Button>
                    </div>
                    <div>
                        <Radio.Group
                            style={style}
                            value={checkAddress.id}
                            onChange={(e) => {
                                const value = e.target.value;
                                const chekcItem = addressList?.find(item => item.id === value)
                                setCheckAddress(chekcItem)
                            }}
                        >
                            {
                                addressList?.map(item => {
                                    return (
                                        <Radio value={item.id}>
                                            <div style={{ display: 'flex', alignItems: 'center',marginLeft: 10 }}>
                                                <div>
                                                    {item?.recipientName || ''} &nbsp;&nbsp;
                                                    {item?.recipientPhone || ''} &nbsp;&nbsp;
                                                    {item?.provinceName || ''}
                                                    {item?.cityName || ''} 
                                                    {item?.regionalName || ''} 
                                                    {item?.addressDetails || ''} 
                                                </div>
                                                {
                                                    item.isDefault  === 1 ? <div className={styles.default}>默认地址</div> : ''
                                                }
                                            </div>
                                        </Radio>
                                    )
                                })
                            }
                            
                        </Radio.Group>
                    </div>
                    <div className={styles.moreAddress}>
                        <span onClick={() => setMoreAdd(!moreAdd)}>
                            更多地址 &nbsp;<DoubleRightOutlined rotate={moreAdd ? -90 : 90} />
                        </span>
                    </div>
                </div>
                <div className={styles.payType}>
                    <div style={{ fontWeight: 600 }}>交易方式</div>
                    <Radio.Group value={transactionModes} style={{ marginTop: 20 }} onChange={(e) => {
                        setTransactionModes(e.target.value)
                    }}>
                        {
                            tradeList?.length > 0 ? 
                            tradeList?.map((item) => {
                                return (
                                    <Radio.Button value={item?.tradeType}>{item?.tradeTypeName}</Radio.Button>
                                )
                            }) : null
                        }
                    </Radio.Group>
                </div>
                <div className={styles.payType}>
                    <div style={{ fontWeight: 600 }}>商品清单</div>
                    <div className={styles.goodsInfo}>
                    {
                        skuList?.length > 0 ? skuList?.map((item, index) => {
                            return (
                                <div style={{ display: 'flex', alignItems: 'center', marginBlock: 10, width: '100%' }}>
                                        <div className={styles.goods}>
                                            <Image width={60} height={60} preview={false} src={item?.picture || item?.goodsPicture} />
                                            <div className={styles.goodsName}>
                                                <div>{item?.goodsName}</div>
                                                <div style={{ display: 'flex' }}><div style={{ fontWeight: 600 }}>规格：</div>{item?.name}</div>
                                            </div>
                                        </div>
                                        <div className={styles.goodsParams}>
                                            <div style={{ marginBottom: 10 }}>单价</div>
                                            <div>¥ {money(item?.price)}</div>
                                        </div>
                                        <div className={styles.goodsParams}>
                                            <div style={{ marginBottom: 10 }}>数量</div>
                                            <InputNumber style={{ width: '160px' }} controls={false} value={quantityList[index]} addonBefore={<PlusOutlined onClick={() => {
                                                const list = cloneDeep(quantityList)
                                                list[index] = list[index] + 1
                                                setQuantityList(list)
                                            }} />} addonAfter={<MinusOutlined onClick={() => {
                                                if (quantityList[index] > 1) {
                                                    const list = cloneDeep(quantityList)
                                                    list[index] = list[index] - 1
                                                    setQuantityList(list)
                                                }
                                            }} />}
                                            onChange={(value) => {
                                                const list = cloneDeep(quantityList)
                                                list[index] = value
                                                setQuantityList(list)
                                            }}
                                            />
                                        </div>
                                    </div>

                                )
                            }) : null
                        }
                    </div>
                </div>
                <div className={styles.payType}>
                    <div style={{ fontWeight: 600 }}>发票信息</div>
                    <div style={{ margin: 20 }}>请在订单完成后，联系客服索要发票</div>
                </div>
                <div className={styles.payType}>
                    <div style={{ fontWeight: 600 }}>支付方式</div>
                    <Radio.Group value={paymentType} style={{ marginTop: 20 }} onChange={(e) => {
                        setPaymentType(e.target.value)
                    }}>
                        {
                            payTyptList?.length > 0 ? 
                            payTyptList?.map((item) => {
                                return (
                                    <Radio.Button value={item?.paymentType}><Image style={{ transform: 'translate(0, -2px)' }} width={18} height={18} preview={false} src={item?.icon} />
                                        <span style={{ marginLeft: '6px' }}>{item?.paymentTypeName}</span>
                                    </Radio.Button>
                                )
                            }): null
                        }
                    </Radio.Group>
                </div>
                <div className={classnames(styles.payType, styles.view)}>
                    <Space size={20} direction="vertical">
                        <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'end' }}>
                            <div style={{ width: '120px', textAlign: 'end' }}>总商品金额：</div>
                            <div style={{ width: '150px', textAlign: 'end' }}>¥ {money(viewData?.totalPrice)}</div>
                        </div>
                        <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'end' }}>
                            <div style={{ width: '120px', textAlign: 'end' }}>运费：</div>
                            <div style={{ width: '150px', textAlign: 'end' }}>¥ {money(viewData?.expressPrice)}</div>
                        </div>
                        <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'end' }}>
                            <div style={{ width: '120px', textAlign: 'end' }}>优惠：</div>
                            <div style={{ width: '150px', textAlign: 'end' }}>- ¥ {money(viewData?.discountPrice)}</div>
                        </div>
                        <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'end' }}>
                            <div style={{ width: '120px', textAlign: 'end' }}>应付总额：</div>
                            <div style={{ width: '150px', color: 'red', textAlign: 'end' }}>¥ {money(viewData?.payablePrice)}</div>
                        </div>
                        <div>
                            收货人：{checkAddress?.recipientName || ''}&nbsp;&nbsp;
                            收货地址：{checkAddress?.recipientPhone || ''} &nbsp;&nbsp;
                                                    {checkAddress?.provinceName || ''}
                                                    {checkAddress?.cityName || ''} 
                                                    {checkAddress?.regionalName || ''} 
                                                    {checkAddress?.addressDetails || ''} 
                        </div>
                    </Space>
                </div>
                <div className={styles.pay}>
                    <Button onClick={createOrderSub} type='primary' size='large'>提交订单</Button>
                </div>
            </div>
            <AddressModal isModalOpen={isModalOpen} setIsModalOpen={setIsModalOpen} afterChange={() => {
                getAddList()
                setMoreAdd(true)
            }} />
        </div>
    )
}

export default orderSettlement;